package com.wande.dataplatform.filecollection.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wande.common.core.exception.ServiceException;
import com.wande.common.mybatis.core.page.TableDataInfo;
import com.wande.dataplatform.filecollection.common.enums.FileCollectionErrorCode;
import com.wande.dataplatform.filecollection.domain.CollectionError;
import com.wande.dataplatform.filecollection.domain.FileRecord;
import com.wande.dataplatform.filecollection.domain.bo.CollectionErrorQuery;
import com.wande.dataplatform.filecollection.domain.vo.CollectionErrorVo;
import com.wande.dataplatform.filecollection.mapper.CollectionErrorMapper;
import com.wande.dataplatform.filecollection.mapper.FileRecordMapper;
import com.wande.dataplatform.filecollection.service.ICollectionErrorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采集错误记录服务实现
 *
 * @author wande
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CollectionErrorServiceImpl implements ICollectionErrorService {

    private final CollectionErrorMapper collectionErrorMapper;
    private final FileRecordMapper fileRecordMapper;

    @Override
    public TableDataInfo<CollectionErrorVo> listErrors(CollectionErrorQuery query) {
        LambdaQueryWrapper<CollectionError> wrapper = buildQueryWrapper(query);
        Page<CollectionErrorVo> page = collectionErrorMapper.selectVoPage(query.build(), wrapper);

        // 填充文件名信息
        page.getRecords().forEach(error -> {
            if (error.getFileId() != null) {
                FileRecord fileRecord = fileRecordMapper.selectById(error.getFileId());
                if (fileRecord != null) {
                    error.setFileName(fileRecord.getFileName());
                }
            }
        });

        return TableDataInfo.build(page);
    }

    @Override
    public CollectionErrorVo getErrorDetail(Long id) {
        CollectionErrorVo error = collectionErrorMapper.selectVoById(id);
        if (error == null) {
            throw new ServiceException(FileCollectionErrorCode.ERROR_RECORD_NOT_FOUND.getMessage());
        }

        // 填充文件名信息
        if (error.getFileId() != null) {
            FileRecord fileRecord = fileRecordMapper.selectById(error.getFileId());
            if (fileRecord != null) {
                error.setFileName(fileRecord.getFileName());
            }
        }

        return error;
    }

    @Override
    public Map<String, Object> getErrorStatistics(CollectionErrorQuery query) {
        LambdaQueryWrapper<CollectionError> wrapper = buildQueryWrapper(query);

        // 总错误数
        Long totalErrors = collectionErrorMapper.selectCount(wrapper);

        // 按错误类型统计
        Map<String, Long> errorTypeStats = collectionErrorMapper.selectList(wrapper)
            .stream()
            .collect(Collectors.groupingBy(CollectionError::getErrorType, Collectors.counting()));

        // 按文件统计错误数
        Map<Long, Long> fileErrorStats = collectionErrorMapper.selectList(wrapper)
            .stream()
            .filter(e -> e.getFileId() != null)
            .collect(Collectors.groupingBy(CollectionError::getFileId, Collectors.counting()));

        // 按任务统计错误数
        Map<Long, Long> taskErrorStats = collectionErrorMapper.selectList(wrapper)
            .stream()
            .collect(Collectors.groupingBy(CollectionError::getTaskId, Collectors.counting()));

        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalErrors", totalErrors);
        statistics.put("errorTypeStats", errorTypeStats);
        statistics.put("fileErrorCount", fileErrorStats.size());
        statistics.put("taskErrorCount", taskErrorStats.size());

        return statistics;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<CollectionError> buildQueryWrapper(CollectionErrorQuery query) {
        return Wrappers.lambdaQuery(CollectionError.class)
            .eq(query.getTaskId() != null, CollectionError::getTaskId, query.getTaskId())
            .eq(query.getFileId() != null, CollectionError::getFileId, query.getFileId())
            .eq(StrUtil.isNotBlank(query.getErrorType()), CollectionError::getErrorType, query.getErrorType())
            .ge(query.getStartTime() != null, CollectionError::getCreateTime, query.getStartTime())
            .le(query.getEndTime() != null, CollectionError::getCreateTime, query.getEndTime())
            .orderByDesc(CollectionError::getCreateTime);
    }
}
